
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.FileSystems;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.PathMatcher;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.StandardCopyOption;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.Enumeration;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

/**
 * 部署client jar
 */
public class DeployEntry {

    private final Path FROM_LIB_PATH;
    private final Path FROM_CLASSES_PATH;
    private final Path TO_EXTEND_PAHT;

    private final Path TO_EXTERNAL_LIB_PATH;
    private final Path TO_EXTERNAL_CLASSES_PATH;

    public DeployEntry(String FIELD_NC_HOME) {
        FROM_LIB_PATH = Paths.get(FIELD_NC_HOME, "hotwebs/nccloud/WEB-INF/classes");
        FROM_CLASSES_PATH = Paths.get(FIELD_NC_HOME, "hotwebs/nccloud/WEB-INF/lib");
        TO_EXTEND_PAHT = Paths.get(FIELD_NC_HOME, "hotwebs/nccloud/WEB-INF/extend/");

        TO_EXTERNAL_LIB_PATH = Paths.get(FIELD_NC_HOME, "external/lib");
        TO_EXTERNAL_CLASSES_PATH = Paths.get(FIELD_NC_HOME, "external/classes");
    }

	public static void run(String home) throws IOException {
		new DeployEntry(home.strip()).run();
	}

    public void run() throws IOException {
        copyConfig();
        moveJar();
        moveClasses();
    }

    private void copyConfig() throws IOException {
        File[] fromFiles = FROM_LIB_PATH.toFile().listFiles();
        for (File fromFile : fromFiles) {
            if (fromFile.getName().endsWith(".jar")) {
                System.out.println(fromFile.getName());
                doCopy(fromFile);
            }
        }

        System.out.println(">>>> move hotwebs/nccloud/WEB-INF/extend/yyconfig/** success >>>>");
    }

    private void doCopy(File fromFile) throws IOException {
        try (JarFile jarFile = new JarFile(fromFile);) {
            Enumeration<JarEntry> entries = jarFile.entries();
            while (entries.hasMoreElements()) {
                JarEntry jarEntry = entries.nextElement();
                String fileName = jarEntry.getName();
                if (fileName.startsWith("yyconfig")) {
                    if (fileName.endsWith(".xml") || fileName.endsWith(".json")) {
                        InputStream input = jarFile.getInputStream(jarEntry);
                        Files.copy(input, TO_EXTEND_PAHT.resolve(fileName), StandardCopyOption.REPLACE_EXISTING);
                    } else {
                        TO_EXTEND_PAHT.resolve(fileName).toFile().mkdirs();
                    }
                }
            }
        }
    }

    private void moveJar() throws IOException {
        File fromPath = FROM_LIB_PATH.toFile();
        for (File fromFile : fromPath.listFiles()) {
            System.out.println(fromFile.getName());
            Files.move(fromFile.toPath(), TO_EXTERNAL_LIB_PATH.resolve(fromFile.getName()), StandardCopyOption.REPLACE_EXISTING);
        }

        System.out.println(">>>> move hotwebs/nccloud/WEB-INF/lib/** success  >>>>");
    }

    private void moveClasses() throws IOException {
        String glob = "glob:**/*.{java,txt,class,xml}";
        final PathMatcher pathMatcher = FileSystems.getDefault().getPathMatcher(glob);
        Files.walkFileTree(FROM_CLASSES_PATH, new SimpleFileVisitor<Path>() {

            @Override
            public FileVisitResult visitFile(Path source, BasicFileAttributes attrs) throws IOException {
                if (pathMatcher.matches(source)) {
                    System.out.println(source);
                    Path relativize = FROM_CLASSES_PATH.relativize(source);
                    System.out.println(relativize);

                    Path target = TO_EXTERNAL_CLASSES_PATH.resolve(relativize);
                    target.getParent().toFile().mkdirs();
                    Files.move(source, target, StandardCopyOption.REPLACE_EXISTING);
                }
                return FileVisitResult.CONTINUE;
            }


            @Override
            public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
                return FileVisitResult.CONTINUE;
            }
        });

        System.out.println(">>>> move hotwebs/nccloud/WEB-INF/classes/** success  >>>>");
    }


}
